import hashlib
from functools import wraps
from utils.ob_log import logger
import time
from flask import request
from app import app
from utils.lian_jie_redis import connect_redis
from config import Config
import random
from ip_check import ip_pi_pei
# from produce_token import get_token
# from flask import make_response


def timer(func):
    @wraps(func)
    def new_func(**kwargs):
        start_time = time.time()
        func(**kwargs)
        end_time = time.time()
        t = end_time - start_time
        if t > 2:
            logger.debug('请求处理时长超过两秒')

    return new_func


@app.before_request
def bai_ming_dan():
    """
    利用钩子来实现白名单和防重放
    :return:
    """
    # 白名单
    user_ip = request.remote_addr
    allow = ip_pi_pei(user_ip)
    if not allow:
        return '<h1 style="text-align:center;">对不起权限不够页面无法访问</h1>'

    # 防重放
    # timestamp = request.args.get('shijianchuo')
    # nonce = request.args.get('nonce')
    # sign = request.args.get('sign')
    # mi_ma = request.args.get('sign')


    shijianchuo = time.time()
    # 时间被修改但是随机数无法或得，方重放只能拿得到，url报文，无法获取到客户端收到的具体消息
    nonce = random.randrange(10000, 99999) + shijianchuo
    sign = 123
    mi_ma = 'ppp'

    # recever_start = shijianchuo + nonce + sign
    # m = hashlib.md5(recever_start.encode())
    # recever_end = m.hexdigest()
    recever_end = 'ppp'

    # 这一步通过表示重放成功
    if mi_ma == recever_end:
        conn = connect_redis()
        data = conn.get(nonce)
        if 60 >= time.time() - shijianchuo:
            if data:
                return '<h1 style="text-align:center;">对不起访问次数过多</h1>'
            else:
                conn.set(name=nonce, value=nonce, ex=Config().get_expires_time())  # 第三个参数表示Redis过期时间,不设置则默认不过期
        else:
            return '<h1 style="text-align:center;">对不起访问次数过多</h1>'

    else:
        return '<h1 style="text-align:center;">关键参数被修改无法访问</h1>'


# @app.after_request
# def token():
#     resp = make_response('set_cookie')
#     token = get_token()
#     resp.set_cookie('token',token)

